<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'order:flow:wx:m8OrderFlowWxIn:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdsSelect>
        <ListSelect v-model:value="itemCodes" :labelValue="itemNames" :selectType="selectType" :checkbox="true"
          :queryParams="queryParams" @select="handSelect" />
      </template>
      <template #m8OrderFlowWxInRdsList>
        <a-button class="mb-2" @click="handleM8OrderFlowWxInRdsAdd(record)"
          v-auth="'order:flow:wx:m8OrderFlowWxIn:edit'" v-if="false">
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <BasicTable @register="registerM8OrderFlowWxInRdsTable" @row-click="handleM8OrderFlowWxInRdsRowClick"
          @edit-change="rowChange" ref="tableRef">
          <template #summary>
            <TableSummary fixed>
              <TableSummaryRow>
                <TableSummaryCell :index="0" align="center">
                  合计：
                </TableSummaryCell>
                <TableSummaryCell :index="1" >
                </TableSummaryCell>
                <TableSummaryCell :index="2" align="center">
                  <span>{{iqtySum}}</span>
                </TableSummaryCell>
                <TableSummaryCell :index="3" >
                </TableSummaryCell>
                <TableSummaryCell :index="4" align="center">
                  <span>{{fmoneySum}}</span>
                </TableSummaryCell>
                <!-- <TableSummaryCell :index="5" :col-span="9">
                </TableSummaryCell> -->
              </TableSummaryRow>
            </TableSummary>
          </template>
        </BasicTable>
        
      </template>
    </BasicForm>
    <template #appendFooter>
      <a-button :loading="loading" @click="handleSp()" v-if="record.inStatus != '4'">
        <Icon icon="simple-line-icons:docs" /> {{ t('保存并审核') }}
      </a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsOrderFlowWxM8OrderFlowWxInForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    M8OrderFlowWxIn,
    m8OrderFlowWxInSave,
    m8OrderFlowWxInForm,
  } from '/@/api/m8/order/m8OrderFlowWxIn';
  import { officeTreeData } from '/@/api/sys/office';
  import { ListSelect } from '/@/components/ListSelect';
  import { basVenTreeData } from '/@/api/bas/ven/basVen';
  import {
    TableSummary,
    TableSummaryCell,
    TableSummaryRow,
  } from 'ant-design-vue';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('order.flow.wx.m8OrderFlowWxIn');
  const { showMessage } = useMessage();
  const record = ref < M8OrderFlowWxIn > ({} as M8OrderFlowWxIn);
  const itemCodes = ref('');
  const itemNames = ref('');
  let queryParams = ref({});
  const selectType = ref('outSelect');
  let loading = ref(false);
  const tableRef = ref();

  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增收料') : t('编辑收料'),
  }));

  const iqtySum = computed(() => {
    // let arr = m8OrderFlowWxInRdsTable.getSelectRows()
    let arr = m8OrderFlowWxInRdsTable.getDataSource()
    let sum = 0
    for (const record of arr) {
      let iqtynum = record.editValueRefs.iqty || 0
      sum += Number(iqtynum);
    }
    return sum.toFixed(2);
  });

  const fmoneySum = computed(() => {
    // let arr = m8OrderFlowWxInRdsTable.getSelectRows()
    let arr = m8OrderFlowWxInRdsTable.getDataSource()
    console.log(arr);
    
    let sum = 0
    for (const record of arr) {
      let fmoneynum = record.editValueRefs.fmoney || 0
      sum += Number(fmoneynum);
    }
    return sum.toFixed(2);
  });
  const inputFormSchemas: FormSchema[] = [
    {
      label: t('单据号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('发料单号'),
      field: 'outDjno',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      required: true,
      dynamicDisabled: true,
    },
    {
      label: t('日 期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
      },
      required: true,
    },
    // {
    //   label: t('供应商'),
    //   field: 'venCode',
    //   component: 'Select',
    //   componentProps: {
    //     dictType: 'm8_ven',
    //     allowClear: true,
    //   },
    //   dynamicDisabled: true,
    //   required: true,
    // },
    {
      label: t('供应商'),
      field: 'venCode',
      fieldLabel: 'basVen.name',
      component: 'TreeSelect',
      componentProps: {
        api: basVenTreeData,
        allowClear: true,
      },
      dynamicDisabled: true,
      required: true,
    },
    {
      label: t('收料人'),
      field: 'receiver.userCode',
      component: 'TreeSelect',
      componentProps: {
        api: officeTreeData,
        params: { isLoadUser: true, userIdPrefix: '', isAll: true, isShowCode: true },
        immediate: true,
        canSelectParent: false,
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('状态'),
      field: 'inStatus',
      component: 'Input',
      componentProps: {
        maxlength: 1,
      },
      required: false,
      show: false,
    },
    {
      label: t('备注'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('选择'),
      field: 'selIds',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdsSelect',
      show: false,
    },
    {
      label: t('收料明细'),
      field: 'm8OrderFlowWxInRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'm8OrderFlowWxInRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 12, md: 24 },
  });

  const [registerM8OrderFlowWxInRdsTable, m8OrderFlowWxInRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleM8OrderFlowWxInRdsDelete.bind(this, record1),
          },
          auth: 'order:flow:wx:m8OrderFlowWxIn:edit',
          ifShow: record.value.allowEdit,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setM8OrderFlowWxInRdsTableData(_res: Recordable) {
    m8OrderFlowWxInRdsTable.setColumns([
      {
        title: t('红字'),
        dataIndex: 'outdid',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('补料ID'),
        dataIndex: 'blId',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('图纸ID'),
        dataIndex: 'orderPic.id',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('图名'),
        dataIndex: 'orderPic.picname',
        width: 180,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
      },
      {
        title: t('收料数 *'),
        dataIndex: 'iqty',
        width: 65,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 8,
          min:0
        },
        editRule: true,
        editable: true,
      },
      {
        title: t('加工单价 *'),
        dataIndex: 'fprice',
        width: 65,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 15,
          min:0
        },
        editRule: true,
        editable: true,
      },
      {
        title: t('金额 *'),
        dataIndex: 'fmoney',
        width: 65,
        align: 'center',
        editRow: true,
        editComponent: 'InputNumber',
        editComponentProps: {
          min:0
        },
        editRule: true,
        editable: true,
      },
      {
        title: t('表面处理'),
        dataIndex: 'bmcl',
        width: 80,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 150,
        },
        editRule: false,
      },
      {
        title: t('规格'),
        dataIndex: 'wxOutRds.cstd',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },

      {
        title: t('材料'),
        dataIndex: 'cmat',
        width: 65,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 200,
        },
        editRule: false,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operName',
        width: 65,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: true,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
      {
        title: t('流程'),
        dataIndex: 'orderFlow.id',
        width: 130,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('工序'),
        dataIndex: 'oper.operCode',
        width: 100,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('累计合格'),
        dataIndex: 'sumHgQty',
        width: 65,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('累计报废'),
        dataIndex: 'sumBfQty',
        width: 65,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('累计返修'),
        dataIndex: 'sumFxQty',
        width: 65,
        align: 'center',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 8,
        },
        editRule: false,
      },
      {
        title: t('订单'),
        dataIndex: 'order.id',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('发料单号'),
        dataIndex: 'outDjno',
        width: 120,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
    ]);
    if (record.value.m8OrderFlowWxInRdsList) {
      record.value.m8OrderFlowWxInRdsList.forEach((item, index) => {
        if (!item.id) {
          item.id = index + 1;
        }
      });
    }
    m8OrderFlowWxInRdsTable.setTableData(record.value.m8OrderFlowWxInRdsList || []);
  }

  async function rowChange({ column, value, record: record1 }) {
    const {
      editValueRefs: { fprice, iqty, fmoney },
    } = record1;
    
    if (column.dataIndex === 'iqty') {
      if ((fprice.value || fprice.value ==0) && iqty.value) {
        fmoney.value = ( fprice.value * iqty.value ).toFixed(2);
      }
    }

    if (column.dataIndex === 'fprice') {
      if ((fprice.value || fprice.value ==0)  && iqty.value) {
        fmoney.value = ( fprice.value * iqty.value ).toFixed(2);
      }
      fprice.value = value==0?'0.00':value
    }

    if (column.dataIndex === 'fmoney') {
      if (iqty.value && (fmoney.value || fmoney.value ==0)) {
        fprice.value = ( fmoney.value / iqty.value ).toFixed(4);
      }
      fmoney.value = value==0?'0.00':value
    }
  }

  function handleM8OrderFlowWxInRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleM8OrderFlowWxInRdsAdd(record) {
    queryParams.value['wxOut.venCode'] = record.venCode;
    document.getElementById('form_item_selIds')?.click();
  }

  function handleM8OrderFlowWxInRdsDelete(record: Recordable) {
    m8OrderFlowWxInRdsTable.deleteTableDataRecord(record);
  }

  /**
   * 选择
   * @param selectData
   */
  function handSelect(selectData) {
    if (selectType.value === 'outSelect') {
      selectData.forEach((item) => {
        m8OrderFlowWxInRdsTable.insertTableDataRecord({
          id: '',
          isNewRecord: true,
          editable: true,
          ...item,
          iqty:
            item.iqty - (item.sumBackQty || 0) - (item.sumInQty || 0) > 0
              ? (item.iqty - (item.sumBackQty || 0) - (item.sumInQty || 0)) * -1
              : item.iqty - (item.sumBackQty || 0) - (item.sumInQty || 0),
          outDid: item.id,
        });
      });
    } else {
      m8OrderFlowWxInRdsTable.insertTableDataRecord({
        id: new Date().getTime(),
        isNewRecord: true,
        editable: true,
      });
    }
  }

  async function getM8OrderFlowWxInRdsList() {
    let m8OrderFlowWxInRdsListValid = true;
    let m8OrderFlowWxInRdsList: Recordable[] = [];
    for (const record of m8OrderFlowWxInRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        m8OrderFlowWxInRdsListValid = false;
      }
      m8OrderFlowWxInRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of m8OrderFlowWxInRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      m8OrderFlowWxInRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!m8OrderFlowWxInRdsListValid) {
      throw { errorFields: [{ name: ['m8OrderFlowWxInRdsList'] }] };
    }
    return m8OrderFlowWxInRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    loading.value = true;
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await m8OrderFlowWxInForm(data);
    record.value = (res.m8OrderFlowWxIn || {}) as M8OrderFlowWxIn;
    setDrawerProps({ showOkBtn: record.value.allowEdit });
    record.value.__t = new Date().getTime();
    queryParams = ref({
      'wxOut.outStatus': '4',
      'wxOut.bred': '0',
      'wxOut.venCode': record.value.venCode,
    });
    setFieldsValue(record.value);
    setM8OrderFlowWxInRdsTableData(res);
    updateSchema([
      {
        field: 'djno',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    loading.value = false;
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      loading.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.m8OrderFlowWxInRdsList = await getM8OrderFlowWxInRdsList();
      // console.log('submit', params, data, record);
      const res = await m8OrderFlowWxInSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
      tableRef.value.setProps({ editable: true });
    } finally {
      loading.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
  async function handleSp() {
    try {
      const data = await validate();
      loading.value = true;
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
        ope: '4',
      };
      data.m8OrderFlowWxInRdsList = await getM8OrderFlowWxInRdsList();
      data.ope = '4';
      // console.log('submit', params, data, record);
      const res = await m8OrderFlowWxInSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      }
      console.log('error', error);
    } finally {
      loading.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>

<style lang="less" scoped>
  :deep(.jeesite-editable-cell__action) {
    display: none;
  }
</style>